﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.Models.SYS.ViewModel;
using KPIS.GERP.WEB.GIMS.Class;
using KPIS.GERP.WEB.GIMS.EmployeeService;
using KPIS.GERP.WEB.GIMS.SysApprovalService;
using KPIS.GERP.WEB.GIMS.UserService;

//using KPIS.GERP.SERVICE.Model;
//using KPIS.GERP.WEB.GIMS.TempService;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    [AccessDeniedAuthorize]
    public class ApprovalTaskController : Controller
	{
        //private AbsenceApprovalWCF.AbsenceApprovalWCFClient absenceApprovalWCFClient = new AbsenceApprovalWCF.AbsenceApprovalWCFClient();
        //private AbsenceApprovalWF.ServiceClient absenceApprovalWFClient = new AbsenceApprovalWF.ServiceClient();
        //private TempService.TempServiceClient tempServiceClient = new TempService.TempServiceClient();
        private MessageService.MessageServiceClient messageServiceClient = new MessageService.MessageServiceClient();
        private SysApprovalService.SysApprovalServiceClient serviceClient = new SysApprovalServiceClient();
        private UserService.UserServiceClient userServiceClient = new UserServiceClient();
        private EmployeeService.EmployeeServiceClient employeeServiceClient = new EmployeeServiceClient();
		public static Guid DaemonWorkflowUniqueId;

		public ActionResult Index(bool noLayout = false)
		{
			List<ApprovalTask> obj;
			obj = (from t in serviceClient.SelectApprovalTasks(GimsMembership.CurrentEmpId)
					   select t).OrderByDescending(t => t.ApprovalTaskId).ToList();
			 
            ViewBag.noLayout = noLayout; 
			return View(obj);
		}

        public ActionResult TaskInbox()
        {
            List<ApprovalTask> obj;
            obj = (from t in serviceClient.SelectApprovalTasks(GimsMembership.CurrentEmpId)
                   select t).OrderByDescending(t => t.ApprovalTaskId).ToList();

            return View(obj);
        }

        public ActionResult TaskMessageInbox(int? ruleApproveGroupSeq, bool noLayout = false)
        {

            //var obj = tempServiceClient.GetMessages(Class.GimsMembership.CurrentEmpCitizen);

            //hrm_ps_employees[] empList;
            //sys_sc_users[] userList;
            //rule_approve_group[] ruleApproveGroupList;
            //rule_approve_type[] ruleApproveTypeList;
            //var ruleapproveList = new TempService.TempServiceClient().RuleApproveList(out empList,
            //                                                                                             out userList,
            //                                                                                             out ruleApproveGroupList,
            //                                                                                             out ruleApproveTypeList).ToList();

            var obj = messageServiceClient.SelectMessage(null, null);
            ViewBag.empList = employeeServiceClient.Select(null,null,true);
            ViewBag.userList = userServiceClient.GetUsers();
            ViewBag.ruleApproveGroupList = serviceClient.SelectApproveProcessGroup();
            ViewBag.ruleApproveTypeList = serviceClient.SelectApproveProcess(null); 
            ViewBag.noLayout = noLayout; 

            if (ruleApproveGroupSeq == null || ruleApproveGroupSeq == 0) return View(obj);

            //var obj2 = obj.Where(o => o.rule_approve_group_seq == ruleApproveGroupSeq);

            var ruleApproveGroupFiltered = serviceClient.SelectApproveProcessGroup().FirstOrDefault(o => o.AppPrcGrpId == ruleApproveGroupSeq.Value);

            if (ruleApproveGroupFiltered == null)
            {
                return RedirectToAction("TaskMessageInbox");
            }
            ViewBag.RuleApproveGroupFiltered = ruleApproveGroupFiltered;


            return View(obj);
        }

        [HttpPost]
        public ActionResult TakeAction(int taskMessageSeq, int wfInstantId, string actionCode, string Reasons, string MessageTitle = null, string backto = "",
             string MessageTitleA = null,string MessageTitleF = null,string MessageTitleN = null,string MessageTitleJ = null,string MessageTitleC = null, bool noLayout = false)
		{
            ViewBag.noLayout = noLayout; 
			try
            {
                //var tempService = new TempService.TempServiceClient();
                //var employeeOnMySql = tempService.GetEmployeeByCitizen(Class.GimsMembership.CurrentEmpCitizen);
                
		    KPIS.GERP.Models.SYS.CommandAction commandAction;
		    switch (actionCode)
		    {
                case "A" : commandAction = CommandAction.Approve;
		            break;
                case "F" : commandAction = CommandAction.Forward;
		            break;
                case "N" : commandAction = CommandAction.SendBack;
		            break;
                case "J" : commandAction = CommandAction.Reject;
		            break;
                case "C" : commandAction = CommandAction.Cancel;
		            break;
                    default: commandAction = CommandAction.Information;
		            break;
		    }
                MessageTitle = MessageTitle ?? MessageTitleA ?? MessageTitleF ?? MessageTitleN ?? MessageTitleJ ?? MessageTitleC;
                var commandActionVm = new CommandActionVM();
                commandActionVm.CommandAction = commandAction;
                commandActionVm.MessageId = taskMessageSeq;
                commandActionVm.ByEmpId = GimsMembership.CurrentEmpId;
                commandActionVm.NewTitle = MessageTitle;
                commandActionVm.Remarks = Reasons;
                serviceClient.ExecuteCommandAction(commandActionVm);
                ; //message absenceApprovalWFClient.ApproveAbsence(wfInstantId, ApprovalUtil.TaskActionFromString(actionCode), employeeOnMySql.emp_seq, Reasons, MessageTitle);
			}
			catch (Exception ex)
			{
                return RedirectToAction("TaskMessageDetails", new
                    {
                        messageFromTakeAction = System.Web.HttpUtility.HtmlEncode("ไม่สามารถทำคำสั่งกับคำขออนุมัตินี้ได้ อาจเกิดจากสถานะคำขอ: <br/>" +
                                                "1. สิ้นสุดลงแล้ว<br/>" +
                                                "2. คำขออนุมัติในระบบ Workflow<br/>" +
                                                "3. ถูกล้างข้อมูลหรือลบไปจากระบบ<br/>"),
                        messageFromTakeActionHide = ex.Message,
                        taskMessageSeq = taskMessageSeq,
                        noLayout = noLayout
                    });
			}
			//if (backto == "Absence")
			//	return RedirectToAction("Index", "Absence");

			//if (backto == "SalaryPromote")
			//	return RedirectToAction("Index", "SalaryPromote");

			return RedirectToAction("Index", new {noLayout = noLayout});
		}

		public ActionResult Details(int approvalTaskSeq)
		{ 
				var obj = (from t in serviceClient.SelectApprovalTasks(GimsMembership.CurrentEmpId)
						   where t.ApprovalTaskId == approvalTaskSeq
						   select t).OrderByDescending(t => t.ApprovalTaskId).FirstOrDefault();

				return View(obj); 
		}

        public ActionResult TaskMessageDetails(int taskMessageSeq, int? ruleApproveGroupSeq, string messageFromTakeAction = "", string messageFromTakeActionHide = "", bool noLayout = false)
        {
            ViewBag.TaskMessageSeq = taskMessageSeq;
            ViewBag.MessageFromTakeAction = messageFromTakeAction;
            ViewBag.MessageFromTakeActionHide = messageFromTakeActionHide;
            ViewBag.NoLayout = noLayout;

            messageServiceClient.ReadMessage(taskMessageSeq, GimsMembership.CurrentEmpId);

            var message = messageServiceClient.SelectMessage(new Message{MessageId = taskMessageSeq}, null).FirstOrDefault();
                ViewBag.MessageModel = message;
                ViewBag.RuleApproveGroupSeq = ruleApproveGroupSeq;
                messageServiceClient.ReadMessage(taskMessageSeq, Class.GimsMembership.CurrentEmpId);

            var approvalTaskDtlId = serviceClient.SelectApprovalTaskDtls(null, message.ApprovalTaskDtlId).FirstOrDefault().ApprovalTaskId;

                List<ApprovalTask> taskList; 
                    taskList = serviceClient.SelectApprovalTasks(GimsMembership.CurrentEmpId).ToList(); 
                var obj = (from t in taskList
                           where t.ApprovalTaskId == approvalTaskDtlId
                           select t).OrderByDescending(t => t.ApprovalTaskId).FirstOrDefault();


                return View(obj);


            //}
        }
         
        public ActionResult RuleApproveList()
        {
            //using (var serviceClient = new TempServiceClient())
            //{
            ViewBag.empList = employeeServiceClient.Select(null,null,true);
            ViewBag.userList = userServiceClient.GetUsers();
            ViewBag.ruleApproveGroupList = serviceClient.SelectApproveProcessGroup();
            ViewBag.ruleApproveTypeList = serviceClient.SelectApproveProcess(null); 
                //hrm_ps_employees[] employeeses;
                //sys_sc_users[] userses;
                //rule_approve_group[] ruleApproveGroups;
                //rule_approve_type[] ruleApproveTypes;
                //var rule_approve = serviceClient.RuleApproveList(out employeeses, out userses, 
                //    out ruleApproveGroups, out ruleApproveTypes);

                //ViewBag.emp = employeeses;
                //ViewBag.user = userses;
                //ViewBag.ruleApproveGroups = ruleApproveGroups;
                //ViewBag.ruleApproveTypes = ruleApproveTypes;
            return View();// rule_approve);
            //}
        }
    }
}
